package com.xcc.dataStructures.demo06_algorithm;

/**
 * 归并排序
 *
 * @author xiaocheng
 * @date 2020/12/4 14:03
 */
public class MergeSort {

    public static void main(String[] args) {
        /*int[] arr = {32, 7, 12, 11, 90, 5, 1};
        sort(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(arr));*/
        int data = 80000000;//8000w数据
        int[] arr = new int[data];
        for (int i = 0; i < data; i++) {
            arr[i] = (int) (Math.random() * data);
        }
//        int[] arr = {32, 7, 12, 11, 90, 5, 1};
        long startTime = System.currentTimeMillis();
        sort(arr, 0, data - 1);
        long endTime = System.currentTimeMillis();
        System.out.println("时长：" + ((endTime - startTime))); //大概耗时13442ms 13s
    }

    /**
     * 递归分割
     */
    public static void sort(int[] arr, int left, int right) {
        int mid = (left + right) / 2;
        if (left < right) {
            sort(arr, left, mid);
            sort(arr, mid + 1, right);
            merge(arr, left, right);
        }
    }

    /**
     * 合并排序
     */
    public static void merge(int[] arr, int left, int right) {
        int mid = (left + right) / 2;
        int i = left;
        int j = mid + 1;
        int k = 0;
        //用于临时存储有序的数据
        int[] temp = new int[right - left + 1];
        while (i <= mid && j <= right) {
            //如果左边的数大于右边的数  存放右边的数
            if (arr[i] > arr[j]) {
                temp[k++] = arr[j++];
            } else {
                //如果左边的数小于右边的数  存放左边的数
                temp[k++] = arr[i++];
            }
        }
        //剩余的左边的数据全部加入到temp数组中
        while (i <= mid) {
            temp[k++] = arr[i++];
        }
        //剩余的右边的数据全部加入到temp中
        while (j <= right) {
            temp[k++] = arr[j++];
        }
        //将原始arr数组中对应的这一段数据进行替换
        System.arraycopy(temp, 0, arr, left, temp.length);
    }

}
